define(function (require, exports, module) {
    'use strict';
    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        notify = require('js/utils/notify'),
        models = require('js/apps/op/models'),
        uploader = require('js/utils/uploader'),
        utils = require('js/utils/tools'),
        moment = require('moment'),
        app = Backbone.history;
    require('datetimepicker');
    var NotificationListView = Backbone.View.extend({
        tagName: "div",
        events: {
            'click a.delete-item': 'toDelete',
            'click #search': 'doSearch',
        },
        initialize: function (options) {
            this.options = options;
            this.collection = new models.NotificationCollection();
            this.collection.bind('change reset remove', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },
        doSearch: function () {
            var options = {},
                searched = {};
            searched.content = $('#searchContent').val();
            if (searched.content) {
                options.content = {
                    $like: searched.content
                }
            }
            utils.saveSearched('op/notify', searched);
            app.navigate(utils.composeQueryString('#op/notify/', options), {
                trigger: true
            });
        },
        toDelete: function (e) {
            utils.deleteItem(e, this.collection);
        },
        renderWithData: function () {
            this.$el.html(this.template({
                items: this.collection.toJSON(),
                searched: utils.getSearched('op/notify')
            }));
            var that = this;
            utils.renderTable('main-list', {
                $orderby: that.options.$orderby || 'id',
                sortCallback: function (field) {
                    that.options.$orderby = field;
                    that.options.$page = 1;
                    var newUrl = utils.composeQueryString('#op/notify/', that.options);
                    app.navigate(newUrl, {
                        trigger: true
                    });
                }
            });
            utils.getPaginator(that.options, this.collection.total, '#op/notify/');

            return this;
        },
        load: function () {
            this.collection.fetch({
                reset: true,
                data: this.options,
                error: function (c, r, o) {
                    notify.notifyResp(r);
                },
            });
        }
    });
    exports.List = Backbone.View.extend({
        el: "#content_wrapper",
        template: "op/NotificationList.html",

        initialize: function (options) {
            this.options = options;
        },
        render: function () {
            var view = new NotificationListView(this.options);
            view.template = this.template;

            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();

            return this;
        }
    });
    var NotificationDetailView = Backbone.View.extend({
        tagName: "div",
        className: "panel-body pn",
        events: {
            'click #save': 'toSaveOrCreate',
            'change #inputAlert': 'toggleAlert',
            'click .remove-filter': 'removeFilter',
            'click #addFilter': 'addFilter',
            'click .switch-key': 'switchKey',
            'click .shortcut': 'quickAdd'
        },
        initialize: function (options) {
            this.model = new models.Notification();
            if (options.id) {
                this.model.set('id', options.id);
            }
            this.model.bind('change reset', this.renderWithData, this);
        },
        render: function () {
            this.$el.html("");
            $(window).scrollTop(0);
            return this;
        },
        toggleAlert: function () {
            if ($('#inputAlert').is(':checked')) {
                $('#alertContent').show();
            } else {
                $('#alertContent').hide();
            }
        },
        toSaveOrCreate: function (e) {
            e.preventDefault();
            if (!utils.simpleCheck('#content-form')) {
                notify.error('错误', '输入错误，请检查');
                return;
            }
            var attrs = utils.getAllInput('#content-form'),
                filter_list = [];
            if (!$('#inputAlert').is(':checked') && attrs.extend) {
                delete attrs.extend.alert;
            }
            if (attrs.extend && attrs.extend.alert && attrs.extend.alert.type == "") {
                delete attrs.extend.alert.type;
            }
            attrs.expire_ts = moment(attrs.expire_ts).unix();
            $('#filter-form .filter').each(function () {
                var data = utils.getAllInput(this),
                    key = $(this).find('.switch-key:first').data('key');
                data['chn'] = {};
                data['chn'][key] = $(this).find('.filter-value:first').val();
                data['chn'][key] = data['chn'][key].split(',');
                filter_list.push(data);
            });
            if (!attrs.extend) attrs.extend = {};
            if (filter_list.length > 0) {
                attrs.extend.filter_list = filter_list;
            }
            attrs.extend = attrs.extend ? JSON.stringify(attrs.extend) : null;
            attrs.content = JSON.stringify(attrs.content);
            this.model.save(attrs, {
                patch: true,
                success: function (model, response) {
                    notify.success('提示', '保存成功！');
                    setTimeout(function () {
                        history.back();
                    }, 500);
                },
                error: function (model, response) {
                    notify.notifyResp(response);
                }
            });

            return false;
        },
        removeFilter: function (e) {
            $(e.target).closest('.filter').remove();
            return false;
        },
        addFilter: function (e) {
            e.preventDefault();
            $('#filter-form').append($('#filterTemplate').html());
            return false;
        },
        switchKey: function (e) {
            var $this = $(e.target);
            if ($this.data('key') == 'include') {
                $this.data('key', 'exclude').html('排除渠道');
            } else {
                $this.data('key', 'include').html('包含渠道');
            }
            return false;
        },
        quickAdd: function (e) {
            e.preventDefault();
            var $this = $(e.target),
                aria = $this.data('aria'),
                $pel = $this.closest('.input-group'),
                $key = $pel.find('.switch-key:first'),
                $el = $pel.find('.filter-value:first');
            switch (aria) {
                case 'allAndroid':
                    $key.data('key', 'exclude').html('排除渠道');
                    $el.val(NOT_ANDROID_CHN.join(','));
                    break;
                case 'allIOS':
                    $key.data('key', 'include').html('包含渠道');
                    $el.val(IOS_CHN.join(','));
                    break;
                case 'allQG':
                    $key.data('key', 'include').html('包含渠道');
                    $el.val(IOS_QG_CHN.join(','));
                    break;
            }
            $pel.find('[data-toggle="dropdown"]').parent().removeClass('open');
            return false;
        },
        renderWithData: function () {
            this.$el.html(this.template({
                info: this.model.toJSON()
            }));
            uploader.getSingleUploader('uploadImage');
            $('#inputExpireTs').datetimepicker({
                format: 'YYYY-MM-DD'
            });
            return this;
        },
        load: function () {
            if (this.model.id) {
                this.model.fetch({
                    reset: true
                });
            } else {
                this.renderWithData();
            }
        }
    });
    exports.Detail = Backbone.View.extend({
        el: "#content_wrapper",
        template: "op/NotificationDetail.html",

        initialize: function (options) {
            this.options = options;
        },
        render: function () {
            var view = new NotificationDetailView(this.options);
            view.template = this.template;

            this.$el.empty();
            this.$el.append(view.render().el);
            view.load();

            return this;
        }
    });

});